<template> 
  <el-card class="form-container" shadow="never">
    <el-form :model="topic" :rules="rules" ref="topicFrom" label-width="150px">

        <el-form-item label="活动标题：" prop="activeTitle">
            <el-input v-model="topic.activeTitle"></el-input>
        </el-form-item>
        <el-form-item label="活动副标题：" prop="activeDes">
            <el-input v-model="topic.activeDes"></el-input>
        </el-form-item>
        <el-form-item label="活动类型：" prop="activeType">
            <el-select v-model="topic.activeType">
                
                <el-option label="精彩" :value="1"></el-option>
                <el-option label="研学" :value="2"></el-option>
                <el-option label="创客" :value="3"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="活动主图：" prop="activeImg">
            <el-upload
            class="avatar-uploader"
            :data="dataObj"
            :action="uploadApi"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="topic.activeImg" :src="topic.activeImg" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <div class="el-upload__tip" v-if="topic.activeType == 1">尺寸为710*378，格式为jpg或png，大小不超过5MB
</div>
            <div class="el-upload__tip" v-if="topic.activeType > 1">尺寸为141*141，格式为jpg或png，大小不超过5MB

</div>
        </el-form-item>
        <el-form-item label="关联商品编号：" prop="refGoodsNumber">
            <el-input v-model="topic.refGoodsNumber"></el-input>
            （可输入3个编号，英文分号隔开，按照输入顺序排序）
        </el-form-item>
        <!-- <el-form-item label="活动排序：" prop="sort">
            <el-input v-model="topic.sort" type="number"></el-input>
        </el-form-item> -->
        <el-form-item label="是否推荐：" prop="recommendStatus">
            <el-radio-group v-model="topic.popActive">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item label="是否置顶：" prop="popActive">
            <el-radio-group v-model="topic.recommendStatus">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item label="是否显示：" prop="showStatus">
            <el-radio-group v-model="topic.showStatus">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item label="活动详情：" prop="activeDt">
            <!-- <tinymce :width="595" :height="300" v-model="topic.activeDt"></tinymce> -->
        <vue-ueditor-wrap v-model="topic.activeDt" :config="myConfig"></vue-ueditor-wrap>
            
        </el-form-item> 
      <!-- <el-form-item label="所属分类：" prop="categoryId">
        <el-select
          v-model="topic.categoryId"
          @change="handlecateChange"
          placeholder="请选择分类">
          <el-option
            v-for="item in cateOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标题：" prop="name">
        <el-input v-model="topic.name"></el-input>
      </el-form-item>

      <el-form-item label="开始时间：" prop="startTime">
        <el-date-picker
          class="input-width"
          v-model="topic.startTime"

          type="datetime"
          :picker-options="pickerOptions1"
          placeholder="请选择开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间：" prop="endTime">
        <el-date-picker
          class="input-width"
          v-model="topic.endTime"

          type="datetime"
          :picker-options="pickerOptions1"
          placeholder="请选择结束时间">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="奖品名称：" prop="awardName">
        <el-input v-model="topic.awardName"></el-input>
      </el-form-item>
      <el-form-item label="参与方式：" prop="attendType">
        <el-input v-model="topic.attendType"></el-input>
      </el-form-item>
      <el-form-item label="内容：" prop="content">
        <el-tabs v-model="activeHtmlName" type="card">
          <el-tab-pane label="电脑端详情" name="pc">
            <tinymce :width="595" :height="300" v-model="topic.content"></tinymce>
          </el-tab-pane>
          <el-tab-pane label="移动端详情" name="mobile">
            <tinymce :width="595" :height="300" v-model="topic.content"></tinymce>
          </el-tab-pane>
        </el-tabs>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" @click="onSubmit('topicFrom')">提交</el-button>
        <el-button v-if="!isEdit" @click="resetForm('topicFrom')">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
import VueUeditorWrap from 'vue-ueditor-wrap';
  import { getToken,get } from '@/utils/auth'
  import {createTopic, getTopic, updateTopic} from '@/api/cms/topic'
  import SingleUpload from '@/components/Upload/singleUpload'
  import {fetchList, deleteSubjectCategory} from '@/api/cms/topicCategory'
  import Tinymce from '@/components/Tinymce'
  import axios from 'axios'
  const QS  = require('qs');
  const defaultTopic={
    // name: ''
    activeTitle: '',
    recommendStatus: false,
    showStatus: false,
    refGoodsNumber: '',
    sort: 0,
    activeDes: '',
    activeDt: '',
    activeImg: '',
    activeType: '',
    // storeId: '1',
    popActive: false
  };
  export default {
    name: 'TopicDetail',
    components:{SingleUpload,Tinymce},
    props: {
      isEdit: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        ruleForm:{
            content:''
          },
            /* ueditor */
            myConfig: {
                // serverUrl: `${__GATEWAYPATH__}/ueditor/ueditorConfig`, // 上传功能的后端服务器接口地址
                UEDITOR_HOME_URL: '/static/UEditor/', // 你的UEditor资源存放的路径,相对于打包后的index.html
                autoHeightEnabled: false, // 编辑器是否自动被内容撑高
                autoFloatEnabled: false, // 工具栏是否可以浮动
                initialFrameHeight: 340, // 初始容器高度
                initialFrameWidth: '100%', // 初始容器高度
                enableAutoSave: true // 关闭自动保存
            },
      //  uploadApi: process.env.BASE_API+'aliyun/oss/upload1',// 上传文件路由
       uploadApi: process.env.BASE_API+'cos/upload',// 上传文件路由
        dataObj: {
          policy: '',
          signature: '',
          key: '',
          ossaccessKeyId: '',
          dir: '',
          host: ''
        },
        //日期选择器配置
        options: [
            
        ],
        pickerOptions1: {
          disabledDate(time) {
            return time.getTime() < Date.now();
          }
        },
        cateOptions:null,
        activeHtmlName: 'pc',
        topic:Object.assign({}, defaultTopic),
        rules: {
        //   name: [
        //     {required: true, message: '请输入专题名称', trigger: 'blur'},
        //     {min: 2, max: 140, message: '长度在 2 到 140 个字符', trigger: 'blur'}
        //   ],
        //   logo: [
        //     {required: true, message: '请输入品牌logo', trigger: 'blur'}
        //   ],
          activeTitle: [
            {required: true, message: '请输入活动名称', trigger: 'blur'},
            {min: 2, max: 140, message: '长度在 2 到 140 个字符', trigger: 'blur'}
          ],
          activeType: [
            {required: true, message: '请选择活动类型', trigger: 'change'},
            // {min: 2, max: 140, message: '长度在 2 到 140 个字符', trigger: 'blur'}
          ],
        //   sort: [
        //     {type: 'number', message: '排序必须为数字'}
        //   ],
        }
      }
    },
    created() {
      if (this.isEdit) {
        getTopic(this.$route.query.id).then(response => {
          this.topic = response.data;
        });
      }else{
        this.topic = Object.assign({},defaultTopic);
      }
    //   this.getCateList();
    },
    methods: {
      getCateList() {
        fetchList({pageNum: 1, pageSize: 100}).then(response => {
          this.cateOptions = [];
        let brandList = response.data.records;
        for (let i = 0; i < brandList.length; i++) {
          this.cateOptions.push({label: brandList[i].name, value: brandList[i].id});
        }
      });
      },
      onSubmit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$confirm('是否提交数据', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              if (this.isEdit) {
                // updateTopic(this.$route.query.id, this.topic).then(response => {
                //   this.$refs[formName].resetFields();
                //   this.$message({
                //     message: '修改成功',
                //     type: 'success',
                //     duration:1000
                //   });
                //   this.$router.back();
                // });
                console.log(321321)
                  this.topic.access_token = getToken()
                  axios.post(process.env.BASE_API + 'active/saveOrUpdate', QS.stringify(this.topic),
                    {
                            headers: {
                                'Authorization': getToken()
                            }    
                    }
                  ).then(res => {
                    this.$refs[formName].resetFields();
                    this.topic = Object.assign({},defaultTopic);
                    this.$message({
                        message: '修改成功',
                        type: 'success',
                        duration:1000
                    });
                this.$router.back();
                  }).catch(err => {
                      console.log(err,888)
                  })
              } else {
                  console.log('新建活动')
                  this.topic.access_token = getToken()
                  axios.post(process.env.BASE_API + 'active/saveOrUpdate', QS.stringify(this.topic),
                    {
                            headers: {
                                'Authorization': getToken()
                            }    
                    }
                  ).then(res => {
                    this.$refs[formName].resetFields();
                    this.topic = Object.assign({},defaultTopic);
                    this.$message({
                        message: '添加成功',
                        type: 'success',
                        duration:1000
                    });
                this.$router.back();
                  }).catch(err => {
                      console.log(err,888)
                  })
            //     createTopic(this.topic).then(response => {
            //       this.$refs[formName].resetFields();
            //       this.topic = Object.assign({},defaultTopic);
            //       this.$message({
            //         message: '提交成功',
            //         type: 'success',
            //         duration:1000
            //       });
            //   this.$router.back();
            //     });
              }
            });

          } else {
            this.$message({
              message: '验证失败',
              type: 'error',
              duration:1000
            });
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
        this.topic = Object.assign({},defaultTopic);
      },
      handleAvatarSuccess(res, file) {
          console.log(res.data)
        this.topic.activeImg = res.data
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg' || file.type == 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传图片只能是 JPG或PNG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      }
    }
  }
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>


